package br.edu.ufcg.dsc.psoo.mymoney.view.action;

import java.util.List;

import org.mentawai.core.BaseAction;
import org.mentawai.filter.AuthenticationFree;

import br.edu.ufcg.dsc.psoo.mymoney.controller.TypeController;
import br.edu.ufcg.dsc.psoo.mymoney.controller.exceptions.InvalidTypeException;
import br.edu.ufcg.dsc.psoo.mymoney.controller.exceptions.TypeNotFoundException;
import br.edu.ufcg.dsc.psoo.mymoney.controller.implementation.TypeControllerImpl;
import br.edu.ufcg.dsc.psoo.mymoney.model.bean.Type;
import br.edu.ufcg.dsc.psoo.mymoney.model.bean.User;
import br.edu.ufcg.dsc.psoo.mymoney.model.dao.TypeDAO;

public class TypeAction extends BaseAction implements AuthenticationFree {

	private TypeController typeController;

	public void setTypeDAO(TypeDAO typeDAO) {
		typeController = new TypeControllerImpl(typeDAO);
	}

	public boolean bypassAuthentication(String innerAction) {

		// if (innerAction != null && innerAction.equals("add")) return true;

		return true;// @FIXME sempre nao autenticar
	}

	public void setLists() {

		Long userId = ((User) getUserSession()).getId();

		List<Type> list = typeController.listAll(userId);
		
//		System.out.println(list.toString());

		output.setValue("typeList", list);
	}

	public String delete(Long id) {

		if (!isPost()) {
			Long userId = ((User) getUserSession()).getId();

			try {
				typeController.delete(id, userId);
			} catch (InvalidTypeException e) {
				addMessage(e.getMessage());
				return ERROR;
			} catch (TypeNotFoundException e) {
				addMessage(e.getMessage());
				return ERROR;
			}

			addMessage("Tipo removido com sucesso!");
			setLists();
			return SHOW;

		} else {
			return ERROR;
		}
	}
	
	public String update() {
		
		if (!isPost()) {
			
			Long id = Long.parseLong(input.getString("id"));
			
			Type type = typeController.loadById(id);

			output.setValue("type", type);

			return SHOW;

		} else {

			Type type = new Type();
			Long id = Long.parseLong(input.getString("id"));
			String name = input.getString("name");
			type.setId(id);
			type.setName(name);
			
			User loggedUser = (User) getUserSession();
			
			type.setUser(loggedUser);

			try {
				typeController.update(type);
			} catch (InvalidTypeException e) {
				addError("defaultError", e.getMessage());
				return SHOW;
			}

			addMessage("Informacoes alteradas com sucesso!");

			return UPDATED;
		}
	}
	public String add() {

		if (!isPost()) {

			setLists();

			return SHOW;

		} else {
			// recebe objeto montado do Input
			Type type = input.getObject(Type.class);
			User u = (User) getUserSession();
			type.setUser(u);

			try {
				typeController.create(type);
			} catch (InvalidTypeException e) {
				addMessage(e.getMessage());
				return ERROR;

			}

			addMessage("Tipo cadastrado com sucesso!");

			setLists();

			return SHOW;
		}
	}
}